package com.crysta1.aitrans;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.google.android.material.button.MaterialButton;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Locale;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private TextView tvAverageScore, tvTotalCount, tvCompletedCount, tvAbandonedCount;
    private TextView tvPotentialValue;
    private ImageView ivStar1, ivStar2, ivStar3;
    private MaterialButton btnStart, btnHistory, btnSettings;
    private DatabaseHelper dbHelper;
    private CardView cardPotential;
    private PttCalculator pttCalculator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();

        dbHelper = new DatabaseHelper(this);
        pttCalculator = new PttCalculator(dbHelper); // 使用新的工具类

        cardPotential = findViewById(R.id.cardPotential);

        cardPotential.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击后启动 PttDetailActivity
                Intent intent = new Intent(MainActivity.this, PttDetailActivity.class);
                startActivity(intent);
            }
        });

        setClickListeners();

        updateStatistics();
    }

    private void initViews() {
        tvAverageScore = findViewById(R.id.tvAverageScore);
        tvTotalCount = findViewById(R.id.tvTotalCount);
        tvCompletedCount = findViewById(R.id.tvCompletedCount);
        tvAbandonedCount = findViewById(R.id.tvAbandonedCount);

        tvPotentialValue = findViewById(R.id.tvPotentialValue);
        ivStar1 = findViewById(R.id.ivStar1);
        ivStar2 = findViewById(R.id.ivStar2);
        ivStar3 = findViewById(R.id.ivStar3);

        btnStart = findViewById(R.id.btnStart);
        btnHistory = findViewById(R.id.btnHistory);
        btnSettings = findViewById(R.id.btnSettings);

        cardPotential = findViewById(R.id.cardPotential);
    }

    private void setClickListeners() {
        btnStart.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, QuizActivity.class)));
        btnHistory.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, HistoryActivity.class)));
        btnSettings.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, SettingsActivity.class)));
    }

    /**
     * 更新统计并计算潜力值 + 按规则更新持久化的星星状态
     */
    private void updateStatistics() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // --- 基础统计 ---
        Cursor totalCursor = db.rawQuery("SELECT COUNT(*) FROM quiz_records", null);
        int totalCount = 0;
        if (totalCursor.moveToFirst()) totalCount = totalCursor.getInt(0);
        totalCursor.close();

        Cursor completedCursor = db.rawQuery("SELECT COUNT(*) FROM quiz_records WHERE score >= 3", null);
        int completedCount = 0;
        if (completedCursor.moveToFirst()) completedCount = completedCursor.getInt(0);
        completedCursor.close();

        Cursor abandonedCursor = db.rawQuery("SELECT COUNT(*) FROM quiz_records WHERE score < 3 OR score = -1", null);
        int abandonedCount = 0;
        if (abandonedCursor.moveToFirst()) abandonedCount = abandonedCursor.getInt(0);
        abandonedCursor.close();

        Cursor avgCursor = db.rawQuery("SELECT AVG(score) FROM quiz_records WHERE score >= 3", null);
        float averageScore = 0;
        if (avgCursor.moveToFirst() && !avgCursor.isNull(0)) averageScore = avgCursor.getFloat(0);
        avgCursor.close();

        tvTotalCount.setText(String.valueOf(totalCount));
        tvCompletedCount.setText(String.valueOf(completedCount));
        tvAbandonedCount.setText(String.valueOf(abandonedCount));
        tvAverageScore.setText(new DecimalFormat("0.00").format(averageScore));

        // --- 使用 PttCalculator 获取最近 60 条单次潜力记录（用于日志与 occurrences 统计） ---
        List<PttCalculator.SinglePotentialEntry> recent = pttCalculator.getRecentSinglePotentials(60);
        ArrayList<Float> singlePotentials = new ArrayList<>();
        ArrayList<Long> timestamps = new ArrayList<>();
        int occurrencesAbove8_inFetched = 0;

        for (PttCalculator.SinglePotentialEntry e : recent) {
            singlePotentials.add(e.singlePotential);
            timestamps.add(e.timestamp);
            if (e.singlePotential > 8.0f) occurrencesAbove8_inFetched++;
        }

        Log.d(TAG, String.format(Locale.getDefault(),
                "fetchedRecords=%d occurrencesAbove8_inFetched=%d",
                singlePotentials.size(), occurrencesAbove8_inFetched));

        // --- 使用 PttCalculator 计算当前整体 PTT（潜力值） ---
        float potentialValue = pttCalculator.computePotentialForAll(); // 由 PttCalculator 统一计算
        DecimalFormat df = new DecimalFormat("0.00");

        // 若没有记录时，PttCalculator 会返回至少 1.0；为兼容老逻辑，当确实无记录可考虑回退到 averageScore（这里保留 PttCalculator 的结果）
        tvPotentialValue.setText(df.format(potentialValue));
        Log.d(TAG, "calculated potentialValue (PTT) = " + potentialValue);

        // --- 状态机：读取持久化的星星状态并处理新增记录 ---
        DatabaseHelper.StarState starState = dbHelper.getStarState();
        int currentSavedStars = starState.starCount;
        long lastProcessedTs = starState.lastProcessedTs;
        Log.d(TAG, "before processing: savedStars=" + currentSavedStars + " lastProcessedTs=" + lastProcessedTs);

        // 取出自 lastProcessedTs 之后的新记录（按时间升序处理，保证顺序性）
        Cursor newRecords = db.rawQuery(
                "SELECT score, difficulty, timestamp FROM quiz_records WHERE timestamp > ? ORDER BY timestamp ASC",
                new String[]{String.valueOf(lastProcessedTs)}
        );

        long maxProcessedTs = lastProcessedTs;
        int addedStars = 0;

        if (newRecords != null) {
            while (newRecords.moveToNext()) {
                if (newRecords.isNull(0)) continue;
                float score = newRecords.getFloat(0);
                String difficulty = null;
                if (!newRecords.isNull(1)) difficulty = newRecords.getString(1);
                long ts = newRecords.isNull(2) ? 0L : newRecords.getLong(2);

                float singlePotential = score * getWeightForDifficulty(difficulty);

                // 更新 maxProcessedTs
                if (ts > maxProcessedTs) maxProcessedTs = ts;

                // 当且仅当当前整体潜力值 > 8 时，才为这些“新记录”增加星星
                if (potentialValue > 8.0f && singlePotential > 8.0f && currentSavedStars < 3) {
                    currentSavedStars++;
                    addedStars++;
                    Log.d(TAG, String.format(Locale.getDefault(),
                            "Adding star for record ts=%d singlePotential=%.2f -> newStars=%d",
                            ts, singlePotential, currentSavedStars));
                } else {
                    Log.d(TAG, String.format(Locale.getDefault(),
                            "Skipped record ts=%d singlePotential=%.2f (potentialValue=%.2f savedStars=%d)",
                            ts, singlePotential, potentialValue, currentSavedStars));
                }

                if (currentSavedStars >= 3) {
                    currentSavedStars = 3;
                    // 达到上限后仍需继续推进 maxProcessedTs（避免重复计数）
                }
            }
            newRecords.close();
        }

        // 根据当前潜力值进行状态调整：
        if (potentialValue <= 5.0f) {
            // 清空星星并把最新记录时间标记为已处理（避免未来补加）
            currentSavedStars = 0;
            // 把 maxProcessedTs 置为最近一条记录的时间（如果 singlePotentials 列表有timestamp可用）
            long fallbackMaxTs = maxProcessedTs;
            if (fallbackMaxTs == lastProcessedTs) {
                // 若没有新Records，尝试从 fetched timestamps 获取最新时间戳
                if (timestamps.size() > 0) {
                    fallbackMaxTs = timestamps.get(0); // 因为 earlier SELECT ORDER BY DESC LIMIT 60，索引0为最新
                }
            }
            dbHelper.clearStarsAndAdvance(fallbackMaxTs);
            Log.d(TAG, "potential <= 5: cleared stars and advanced lastProcessedTs to " + fallbackMaxTs);
        } else {
            // 如果有新 processed ts，要保存 lastProcessedTs 为 maxProcessedTs（即使没有增加星，也要避免重复处理）
            if (maxProcessedTs > lastProcessedTs) {
                dbHelper.saveStarState(currentSavedStars, maxProcessedTs);
                Log.d(TAG, "saved star state: stars=" + currentSavedStars + " lastProcessedTs=" + maxProcessedTs);
            } else {
                // 没有新记录，仅保存星星数量变化（当 addedStars >0）
                if (addedStars > 0) {
                    dbHelper.saveStarState(currentSavedStars, lastProcessedTs);
                    Log.d(TAG, "saved star count increased (no ts change) to " + currentSavedStars);
                } else {
                    Log.d(TAG, "no new records and no star change; nothing saved.");
                }
            }
        }

        // UI 展示星星
        ivStar1.setVisibility(currentSavedStars >= 1 ? View.VISIBLE : View.GONE);
        ivStar2.setVisibility(currentSavedStars >= 2 ? View.VISIBLE : View.GONE);
        ivStar3.setVisibility(currentSavedStars >= 3 ? View.VISIBLE : View.GONE);

        // 流彩背景：当潜力值 > 8 时显示
        if (potentialValue > 8.0f) {
            cardPotential.setBackgroundResource(R.drawable.gradient_high);
        } else {
            cardPotential.setBackgroundResource(R.color.card_background);
        }
    }

    /**
     * 根据 difficulty 返回权重（与 PttCalculator 保持一致以防误差）
     */
    private float getWeightForDifficulty(String difficulty) {
        if (difficulty == null) return 1.0f;
        String d = difficulty.trim().toLowerCase(Locale.ROOT);
        switch (d) {
            case "简单":
            case "e":
            case "easy":
                return 0.5f;
            case "适中":
            case "m":
            case "medium":
                return 0.8f;
            case "困难":
            case "h":
            case "hard":
                return 1.0f;
            case "仿真":
            case "r":
            case "real":
            case "simulation":
                return 1.1f;
            default:
                if (d.startsWith("e")) return 0.5f;
                if (d.startsWith("m")) return 0.8f;
                if (d.startsWith("h")) return 1.0f;
                if (d.startsWith("r")) return 1.1f;
                return 1.0f;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateStatistics();
    }
}
